/*
 * ForInstruction.java
 * 
 * last update: 16.01.2010 by Stefan Saru
 * 
 * author:	Power(power@kermit.cs.pub.ro)
 * 
 * Obs:
 */

package engine;

class ForInstruction extends DefaultInstruction{
	Expression cond;
	DefaultInstruction body, update, initial;

	ForInstruction(NameSpace ns, int db, InstructionDescription desc,
			DefaultInstruction initial, Expression cond,
			DefaultInstruction update,
			DefaultInstruction body, DefaultInstruction next)
			{
		super(ns, db, desc);
		this.cond = cond;
		this.body = body;
		this.update = update;
		this.initial = initial;
		if (initial != null)
			initial.append(this);
		if(body != null)
			body.append(this);
		if (update != null)
			update.append(this);
		add(next);
			}

	public Instruction next() {
		switch (state) {
		case 0:
			state = 1;
			if (initial != null)
				return initial;
			return this;
		case 1:
			state = 2;
			if(body != null)
				return body;
			return this;
		case 2:
			state = 1; //here we actually looooop
			if(update != null)
				return update;
			else return this;
		case 3:
			state = 0;
			return next;
		}
		throw new Error("illegal instruction state");
	}

	public void execute()
	throws InterpretTimeException, SimulationStoppedException
	{
		switch (state) {
		case 0:
			waitToRun();
			xConsole.trace(toString());
			break;
		case 1:
			try{
				if(cond != null)
					if(!cond.evaluate().isTrue()) state = 3;
			}catch(InterpretTimeException ex){
				xConsole.dumpStack(ex);
				throw new InterpretTimeException(desc + ": error:" + ex);
			}
		}
	}

}
